from pyvis.network import Network
import networkx as nx
import matplotlib.cm as cm
import matplotlib.colors as colors
# 加载之前保存的GEXF文件
G = nx.read_gexf("data/network_graph.gexf")

# 若未保存过，直接使用现有图 G 即可
net = Network(height="800px", width="100%", bgcolor="#ffffff", font_color="black", notebook=True, directed=True)

# 节点海拔用于颜色映射
elevations = [float(G.nodes[node]['elevation']) for node in G.nodes()]
min_elev, max_elev = min(elevations), max(elevations)
norm = colors.Normalize(vmin=min_elev, vmax=max_elev)
cmap = cm.get_cmap('YlGnBu')

# 添加节点（明确设置label）
for node in G.nodes(data=True):
    node_id = node[0]
    node_attrs = node[1]
    elevation = float(node_attrs['elevation'])
    color = colors.to_hex(cmap(norm(elevation)))

    net.add_node(node_id, 
                 label=str(node_id),   # ← 关键在这里明确指定label
                 title=f"Elevation: {elevation}<br>Population: {node_attrs['population']}<br>GDP: {node_attrs['gdp']}", 
                 color=color,
                 size=15)

# 添加边
for source, target in G.edges():
    net.add_edge(source, target)

# 提供布局调节按钮
net.show_buttons(filter_=['physics'])

# 保存可视化的 HTML
net.save_graph("html/network_graph_with_labels.html")
net.show("html/network_graph_with_labels.html", notebook=False)

# # 根据节点的海拔设置节点颜色
# elevations = [float(G.nodes[node]['elevation']) for node in G.nodes()]
# min_elev, max_elev = min(elevations), max(elevations)

# # 使用colormap映射海拔到颜色
# import matplotlib.cm as cm
# import matplotlib.colors as colors

# norm = colors.Normalize(vmin=min_elev, vmax=max_elev)
# cmap = cm.get_cmap('YlGnBu')

# net = Network(height="800px", width="100%", bgcolor="#ffffff", font_color="black", notebook=True)

# for node in G.nodes(data=True):
#     node_id = node[0]
#     node_attrs = node[1]
#     elevation = float(node_attrs['elevation'])
#     color = colors.to_hex(cmap(norm(elevation)))
    
#     net.add_node(node_id, 
#                  label=node_id, 
#                  title=f"Elevation: {elevation}<br>Population: {node_attrs['population']}<br>GDP: {node_attrs['gdp']}", 
#                  color=color)

# # 添加边
# for source, target in G.edges():
#     net.add_edge(source, target)

# # 可交互的调节布局参数
# net.show_buttons(filter_=['physics'])

# # 保存并查看网络
# net.save_graph("network_graph_with_features.html")
# net.show("network_graph_with_features.html")
